﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI.CustomFilter
{
    /// <summary>
    /// 模型验证过滤器
    /// </summary>
    public class ModelValidateFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                //获取验证失败的模型字段
                var errors = context.ModelState
                    .Where(e => e.Value.Errors.Count > 0)
                    .Select(e => e.Value.Errors.First().ErrorMessage)
                    .ToList();
                var str = string.Join("|", errors);
                //设置返回内容
                JsonResult result = new JsonResult(new
                {
                    Code = 10000,
                    Msg = $"数据验证:{str}"
                });
                context.Result = result;
            }
        }
    }
}
